package com.ft.adbix.core;

import android.os.AsyncTask;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTask extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        String filePath = params[0];
        String apkUrl = params[1];
        try {
            URL url = new URL(apkUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            // 检查是否连接成功
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return null;
            }
            // 创建输入流
            InputStream inputStream = new BufferedInputStream(connection.getInputStream());
            FileOutputStream fileOutput = new FileOutputStream(filePath);
            byte[] data = new byte[1024];
            int count;
            while ((count = inputStream.read(data)) != -1) {
                fileOutput.write(data, 0, count);
                publishProgress(count);
            }
            fileOutput.flush();
            fileOutput.close();
            inputStream.close();
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected void onPostExecute(String result) {
        // 下载完成后的处理，弹出安装APK的对话框等
    }
}